import java.util.concurrent.PriorityBlockingQueue;

public class Test16 {
    //MyTimer 描述定时器任务
    static class MyTimer implements Comparable<MyTimer>{
        private Runnable runnable;
        private long myTime;

        public MyTimer(Runnable runnable, long myTime) {
            this.runnable = runnable;
            this.myTime = System.currentTimeMillis() + myTime;
        }
        public void run(){
            runnable.run();
        }
        @Override
        public int compareTo(MyTimer o) {
            return (int)(this.myTime - o.myTime);
        }
    }
    //存放所有定时器任务,并扫描是否执行
    static class RunMyTimer{
        PriorityBlockingQueue<MyTimer> queue = new PriorityBlockingQueue<>();
        private Object object = new Object();
        public void myPut(Runnable runnable,long myTime) {
            MyTimer myTimer = new MyTimer(runnable,myTime);
            queue.put(myTimer);
           synchronized (object){
               object.notify();
           }
        }
        public RunMyTimer(){
            Thread thread = new Thread(){
                @Override
                public void run() {
                    try {
                        while (true){
                            MyTimer myTimer = queue.take();
                            long time = System.currentTimeMillis();
                            if (time < myTimer.myTime){
                                queue.put(myTimer);
                                synchronized (object){
                                    object.wait(myTimer.myTime - time);
                                }
                            }else {
                                myTimer.run();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        RunMyTimer runMyTimer = new RunMyTimer();
        for (int i = 0; i < 100; i++) {
            int tmp = i;
            System.out.println("第" + i + "次任务");
            runMyTimer.myPut(new Runnable() {
                @Override
                public void run() {
                    System.out.println(tmp);
                }
            },1000);
        }
    }

}
